import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as action from "../../../action";
import { Sticky } from "react-vant";
import { Toast } from 'react-vant';
import LazyLoad from 'react-lazyload'
export class index extends Component {
  componentDidMount() {
    this.props.getCarList();
  }
  componentDidUpdate(){
    this.refs['H2'+ this.state.ind].scrollIntoView({behavior:'smooth'})
  }
  // 加加方法
  sub(index) {
    this.props.sub(index);
    this.props.zjqq();
    Toast('已取消');
  }
  add(index) {
    this.props.add(index);
    this.props.zjqq();
    Toast('已加入');
  }
  remove(item) {
    if (item.cont > 0) {
      this.props.remove(item)
      Toast('已加入购物车');
    }else{
      Toast('至少选择一个');
    }
  }
  render() {
    let { carlist, NewList } = this.props;
    console.log(NewList);
    console.log(this.props);
    return (
      <div className="car">
        <Sticky>
          <div>66666666</div>
        </Sticky>
        {carlist && carlist.length
          ? carlist.map((item, index) => {
            return (
              <div key={index}>
              <LazyLoad debounce={2000}></LazyLoad>
                <img src={item.img} alt="" onClick={() => {
                  this.props.history.push({
                    pathname: "/detail",
                    state: item,
                  });
                }} />
                <span>{item.title}</span>
                <span className="price">{item.price}</span>
                {/* 加加 */}
                <button onClick={this.sub.bind(this, index)}>-</button>
                {item.cont}
                {/* 减减 */}
                <button onClick={this.add.bind(this, index)}>+</button>
                {/* 加入购物车 传item 别单一传id */}
                <button onClick={this.remove.bind(this, item)}>加入购物车</button>
              </div>
            );
          })
          : "asd "}
      </div>
    );
  }
}

const mapStateToProps = ({ RoduxList }) => {
  return {
    ...RoduxList,
  };
};

const mapDispatchToProps = (dispatch) => bindActionCreators(action, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(index);
